﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Coupon_Manager_ProcessLayer;

namespace Coupon_Manager_ActionLayer
{
    public class CouponAction : IDisposable
    {
        private CouponManagerDataContext _context { get; set; }

        public CouponAction(string connectionString)
        {
            this._context = new CouponManagerDataContext(connectionString); 
        }

        ~CouponAction()
        {
            this.Dispose(false);
        }

        public void Dispose()
        {
            this.Dispose(true);
        }

        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                this._context.Dispose();
                GC.SuppressFinalize(this);
            }
        }

        public void InsertCoupon(string upc, string description, decimal discount, int purchaseQuantity, int category, DateTime expiration)
        {
            try
            {
                _context.Coupons.InsertOnSubmit(new Coupon()
                {
                    UPC = upc,
                    Description = description,
                    Discount = discount,
                    PurchaseQuantity = purchaseQuantity,
                    Category = category,
                    Expiration = expiration
                });
                _context.SubmitChanges();
            }
            catch (Exception)
            {
            }
        }

        public void UpdateCoupon(int id, string upc, string description, decimal discount, int purchaseQuantity, int category, DateTime expiration)
        {
            try
            {
                Coupon coupon = _context.Coupons.Single(c => c.ID == 0);

                coupon.UPC = upc;
                coupon.Description = description;
                coupon.Discount = discount;
                coupon.PurchaseQuantity = purchaseQuantity;
                coupon.Category = category;
                coupon.Expiration = expiration;

                _context.SubmitChanges();
            }
            catch (Exception)
            {
                
                throw;
            }
        }
        public object GetCoupons()
        {
            try
            {
                return new BindingList<Coupon>(_context.Coupons.ToList());
            }
            catch (Exception)
            {
                return null;
            }
        }

    }
}
